<template>
  <!-- 订单列表 -->
  <view class="order">
    <view v-if="info.token" class="content">
      <scroll-view
        class="list"
        scroll-y="true"
        :refresher-triggered="refresherTriggered"
        refresher-enabled="true"
        scroll-with-animation="true"
        enable-back-to-top="true"
        @scrolltolower="getMore"
        @refresherrefresh="refreshList"
        show-scrollbar="true"
        v-if="list.length && !refresherTriggered"
      >
        <view
          class="list-item"
          v-for="item in list"
          :key="item.orderNo"
          :data-item="item"
          @click="goTicketDetail"
        >
          <view class="top">
            <!-- <text class="top1">item.departDate</text> -->
            <text class="top2">{{ item.createTime | formatDate }}</text>
          </view>
          <view class="middle">
            <view class="middle_top">
              <view class="time">{{
                (currentDate + " " + item.departTime) | formatDateTime
              }}</view>
              <view class="time">{{
                (currentDate + " " + item.departTime) | formatDateTime
              }}</view>
              <view class="price">￥{{ item.amount }}</view>
            </view>
            <view class="plate_number ">
              <view class="text">{{
                item.busNo || item.schCode || "未知"
              }}</view>
              <image
                class="img"
                src="../../static/images/dd_icon_jtnormal.png"
              ></image>
            </view>
            <view class="middle_bottom">
              <view class="station">
                <view class="omitted">{{ item.departStationName }}</view>
              </view>
              <view class="station">
                <view class="omitted">{{ item.destStationName }}</view>
              </view>
              <view class="status">{{ item.status | formatStatus }}</view>
            </view>
          </view>
          <view class="bottom">
            <view
              v-if="item.status == 'SUCCESS' || item.status == 'PART_REFUND'"
              class="btn btn1"
              @click.stop="returnTicket(item)"
              >立即退票</view
            >
            <!-- <view  class="btn btn2" @click.stop="goTicketDetail">立即开票</view> -->
            <view v-if="item.status == 'CREATED'" class="btn btn3"
              >取消订单</view
            >
            <view v-if="item.status == 'CREATED'" class="btn btn4"
              >立即支付</view
            >
          </view>
        </view>
      </scroll-view>
      <view v-else class="loading"
        ><my-loading
          @refresh="refreshList"
          :loading-type="loadingType"
          :loading-text="loadingText"
          :refresh-btn="refreshBtn"
        ></my-loading
      ></view>
    </view>
    <view v-else class="loading"
      ><my-loading
        loading-type="no_trips"
        loading-text="您尚未登录"
        :refresh-btn="false"
      ></my-loading
    ></view>
  </view>
</template>

<script>
// 备注 订单字段
// id;
// 客票订单号orderNo;
// 系统供应商订单号providerOrderNo;
// 商户号merchantNo;
// 客票供应商标识providerId
// 下单的用户标识userId;
// 用户类型userType;
// 扫呗流水订单号outTradeNo;
// 通道订单号，如支付宝、微信channelTradeNo;
// 支付时间,yyyyMMddHHmmsspayTime;
// 支付流水号（terminal_trace)payTrace;
// 支付方式payType;
// 下单时间createTime;
// 订单金额amount;
// 购票人姓名private String buyerName;
// 购票人证件号码buyerCertNo;
// 购票人证件类型buyerCertType;
// 购票人手机号buyerPhone;
// 班次idschId;
// 班次编号schCode;
// 出发省编号departProvCode;
// 出发省名departProvName;
// 出发城市编号departCityCode;
// 出发城市名departCityName;
// 出发站iddepartStationId;
// 出发站codedepartStationCode;
// 出发站名departStationName;
// 出发日期departDate;
// 出发时间departTime;
// 到达站id destStationId;
// 到达站名destStationName;
// 车次号busNo;
// 车型busType;
// 距离，单位公里distance;
// 车票列表tickets;
// 订单状态status;
import { mapState, mapMutations } from "vuex";
// components
import myLoading from "@/components/myLoading/myLoading.vue";
// api
import { $userOrder, $ordersClose } from "../../service/index";
// utils
import { myShowToast, myShowModal } from "../../utils/utils.js";
export default {
  components: { myLoading },
  data() {
    return {
      refresherTriggered: false, // 设置当前下拉刷新状态，true 表示下拉刷新已经被触发，false 表示下拉刷新未被触发
      list: [], // 订单列表
      currentType: "", // 当前查询的订单状态类型
      currentPage: 0, // 页码
      totalPage: 0, // 总条数
      loadingType: "no_trips",
      loadingText: "",
      refreshBtn: false,
      currentDate: this.$dayjs().format("YYYY-MM-DD"), // 当前日期
    };
  },
  computed: mapState(["info", "orderType"]),
  watch: {
    currentType(val, oldVal) {
      console.log(val, oldVal);
      this.currentPage = 0;
      this.totalPage = 0;
      this.info.token ? this.getOrders() : ""; //登录了才能查订单
    },
  },
  filters: {
    formatStatus(val) {
      const statuss = {
        CREATED: "待支付", // 新创建  -- 立即支付  删除订单（撤销取消订单）
        SUCCESS: "已出票", // 购票完成 -- 退款按钮
        CANCEL: "已撤销", // 订单创建完成未支付
        REFUNDED: "已退款",
        PART_REFUND: "部分退款",
        FAIL: "失败",
      };
      return statuss[val] || "";
    },
  },
  methods: {
    ...mapMutations(["cancelRequest", "updateOrderDetail", "updateOrderType"]),
    // 触底加载下一页
    getMore() {
      console.log("getMore");
      if (this.currentPage + 1 == this.totalPage) {
        // 当前页已经是最后一页
        return;
      }
      this.currentPage++;
      this.getOrders();
    },
    // 下拉刷新
    refreshList() {
      console.log("refreshList");
      this.currentPage = 0;
      this.totalPage = 0;
      this.getOrders();
    },
    // 退票
    returnTicket(item) {
      this.updateOrderDetail(item); // 更新订单详情
      uni.navigateTo({
        // 跳转退票页面
        url: "../../order/returnTicket/returnTicket",
      });
      // this.ordersClose(item.id);
    },
    // 订单详情
    goTicketDetail(e) {
      const item = e.currentTarget.dataset.item;
      this.updateOrderDetail(item);
      console.log("dddiii", item);

      uni.navigateTo({
        url: "../../order/orderDetail/orderDetail",
      });
    },
    // 开票 ？？？
    writeTicket() {
      uni.navigateTo({
        url: "../../order/buyTicket/buyTicket",
      });
    },
    // 订单查询
    getOrders() {
      if (this.refresherTriggered) {
        return;
      }
      this.refresherTriggered = true;
      const statuss = {
        orderAll: "",
        orderPending: "CREATED",
        orderNotTravel: "SUCCESS",
      }; // CREATED, PAID, NOTIFIED, CANCELED, REFUNDED, PAYING, TRAVELING
      const params = {
        page: this.currentPage,
        size: 10,
        status: statuss[this.orderType] || "",
      };
      console.log(params.status);
      $userOrder(params)
        .then((res) => {
          const data = res.data;
          this.refresherTriggered = false;
          if (!data.success) {
            myShowModal(data.message || "网络错误");
            this.loadingText = "未查询到订单信息";
            this.refreshBtn = true;
            return;
          }
          if (this.currentPage == 0) {
            // 第一页
            data.content.content;
            if (!data.content.content || !data.content.content.length) {
              this.loadingText = "未查询到订单信息";
              this.list = [];
              this.refreshBtn = true;
              return;
            }
            let temp = data.content.content;
            if (params.status == "SUCCESS") {
              temp = temp.filter((i) => {
                return this.$dayjs(new Date()).isBefore(
                  this.$dayjs(i.departDate + "," + i.departTime)
                );
              });
            }

            console.log(temp);

            this.list = temp;
            this.totalPage = data.content.totalPages;
          } else {
            // 下一页
            // const list = this.list;
            // this.list = list.concat(data.content.content || []);
            let temp = data.content.content;
            if (params.status == "SUCCESS") {
              temp = temp.filter((i) => {
                return this.$dayjs(new Date()).isBefore(
                  this.$dayjs(i.departDate + "," + i.departTime)
                );
              });
            }
            console.log(temp);

            this.list.push(...temp);
          }
        })
        .catch((err) => {
          this.loadingType = "no_network";
          this.loadingText = "哎呀，网络出错了";
          this.refresherTriggered = false;
          this.refreshBtn = true;
          this.list = [];
          console.log(err);
        });
    },
    // 刷新重试
    refresh() {
      this.getOrders();
    },
    // 关闭订单并退票
    ordersClose(id) {
      $ordersClose({}, id)
        .then((res) => {
          const data = res.data;
          console.log(data);
          if (!data.success) {
            myShowModal(data.message || "网络错误");
            return;
          }
          myShowToast("关闭成功");
          this.refresh();
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
  onLoad(query) {
    console.log(query);

    // this.info.token && this.getOrders();
    uni.$once("hasLogin", (data) => {
      console.log("监听到事件hasLogin,携带参数hasLogin为：" + data.hasLogin);
      data.hasLogin && this.getOrders(); // 登录了才能查订单
    });
  },
  onShow() {
    const title = {
      orderAll: "全部订单",
      orderPending: "待付款",
      orderNotTravel: "未出行",
    };
    this.currentType = this.orderType;
    uni.setNavigationBarTitle({
      title: title[this.orderType] || "全部订单",
    });
    this.info.token && this.getOrders();
  },
};
</script>

<style lang="scss" scoped>
.order {
  background-color: #f4f6f9;
  .content {
    .list {
      width: 710rpx;
      height: 100vh;
      padding: 0 20rpx;
      .list-item {
        box-shadow: 0rpx 6rpx 16rpx 0rpx rgba(230, 235, 244, 0.8);
        border-radius: 16rpx;
        margin: 20rpx 0;
        background: #ffffff;
        padding: 0 32rpx;
        .top {
          padding: 40rpx 0 37rpx 0;
          .top1 {
            display: inline-block;
            background: rgba(42, 105, 255, 1);
            border-radius: 4rpx;
            font-size: 20rpx;
            font-weight: 300;
            height: 28rpx;
            line-height: 28rpx;
            padding: 0 6rpx;
            color: rgba(255, 255, 255, 1);
            margin-right: 15rpx;
            vertical-align: 4rpx;
          }
          .top2 {
            display: inline-block;
            font-size: 28rpx;
            font-weight: 500;
            color: rgba(121, 132, 152, 1);
          }
        }
        .middle {
          border-bottom: 1rpx dashed rgba(209, 215, 225, 1);
          position: relative;
          .middle_top {
            display: flex;
            justify-content: space-between;
            .time {
              font-size: 36rpx;
              font-weight: 800;
              color: rgba(51, 51, 51, 1);
              overflow: hidden;
            }
            .time:first-child {
              flex: 2.5;
            }
            .time:nth-child(2) {
              flex: 1.5;
            }
            .price {
              flex: 1;
              font-size: 32rpx;
              font-weight: bold;
              color: rgba(254, 112, 42, 1);
              text-align: right;
            }
          }
          .middle_bottom {
            display: flex;
            justify-content: space-between;
            padding: 29rpx 0 40rpx 0;
            .station {
              overflow: hidden;
              font-size: 24rpx;
              font-weight: bold;
              color: rgba(51, 51, 51, 1);
              .omitted {
                width: 200rpx;
              }
            }
            .station:first-child {
              flex: 2.5;
            }
            .station:nth-child(2) {
              flex: 1.5;
            }
            .status {
              flex: 1;
              font-size: 28rpx;
              font-weight: bold;
              color: rgba(51, 51, 51, 1);
              text-align: right;
            }
          }
          .plate_number {
            position: absolute;
            top: 32rpx;
            left: 30%;
            text-align: center;
            .text {
              font-size: 20rpx;
              font-weight: 500;
              color: rgba(121, 132, 152, 1);
            }
            .img {
              position: relative;
              top: -20rpx;
              width: 64rpx;
              height: 12rpx;
            }
          }
        }
        .bottom {
          padding: 24rpx 0 0 24rpx;
          position: relative;
          display: flex;
          justify-content: flex-end;
          flex-wrap: wrap;
          .btn {
            margin: 0 0 20rpx 29rpx;
            width: 148rpx;
            height: 56rpx;
            border-radius: 28rpx;
            line-height: 56rpx;
            font-weight: bold;
            font-size: 24rpx;
            text-align: center;
          }
          .btn1 {
            background: linear-gradient(
              90deg,
              rgba(34, 100, 255, 0.1) 0%,
              rgba(52, 113, 255, 0.1) 99%
            );
            // box-shadow:0rpx 8rpx 12rpx 0rpx rgba(25,102,255,0.32);
            color: rgba(36, 101, 255, 1);
          }
          .btn2 {
            background: linear-gradient(
              90deg,
              rgba(34, 100, 255, 1) 0%,
              rgba(52, 113, 255, 1) 99%
            );
            color: rgba(255, 255, 255, 1);
          }
          .btn3 {
            background: linear-gradient(
              90deg,
              rgba(254, 112, 42, 0.1) 0%,
              rgba(255, 130, 7, 0.1) 100%
            );
            // box-shadow:0rpx 8rpx 12rpx 0rpx rgba(25,102,255,0.32);
            color: rgba(254, 112, 42, 1);
          }
          .btn4 {
            background: linear-gradient(
              90deg,
              rgba(254, 112, 42, 1) 0%,
              rgba(255, 130, 7, 1) 100%
            );
            color: rgba(255, 255, 255, 1);
          }
          .btn5 {
            background: rgba(0, 0, 0, 0.1);
            // box-shadow:0rpx 8rpx 12rpx 0rpx rgba(25,102,255,0.32);
            color: rgba(153, 153, 153, 1);
          }
          .btn6 {
            background: rgba(153, 153, 153, 1);
            color: rgba(255, 255, 255, 1);
          }
        }
        .bottom::before,
        .bottom::after {
          content: "";
          position: absolute;
          width: 40rpx;
          height: 40rpx;
          background-color: #f4f6f9;
          border-radius: 50%;
          top: -20rpx;
        }
        .bottom::before {
          left: -50rpx;
        }
        .bottom::after {
          right: -50rpx;
        }
      }
    }
  }
  .loading {
    height: 100vh;
    /deep/ .loading {
      margin: 0 !important;
    }
  }
}
</style>
